package cn.hzw.supermarket.activity;

import static cn.hzw.supermarket.util.HttpUtil.sendHttpRequest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hzw.supermarket.R;
import cn.hzw.supermarket.adapter.RecyclerViewAdapter;
import cn.hzw.supermarket.databinding.ActivitySnackBinding;
import cn.hzw.supermarket.domain.Goods;

public class SnackActivity extends AppCompatActivity implements OnBannerListener {
    private ActivitySnackBinding binding;
    public static List<Goods> goodsList = new ArrayList<>();
    public static String pic;
    Goods goods = new Goods();
    RecyclerViewAdapter recyclerViewAdapter;
    Context context;
//    RecyclerView goodsOne;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏标题栏以及状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        /**标题是属于View的，所以窗口所有的修饰部分被隐藏后标题依然有效,需要去掉标题**/
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = ActivitySnackBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        binding.layoutTitle.tvTitle.setText("商品页面");
        binding.layoutTitle.ivBack.setOnClickListener(view -> {
            finish();
        });

        binding.lvList.setLayoutManager(new LinearLayoutManager(this));
        goods.setGoodscategory(1);
        Log.d("TAG321", "onCreate: "+goods.getGoodscategory());
        postRequest("/goodsinfo/category", goods.getGoodscategory());
        initView();
    }

    private void initView() {
        //图片资源
        int[] imageResourceID = new int[]{R.mipmap.jianguolibao, R.mipmap.binqilin, R.mipmap.shousimianbao, R.mipmap.leshishupian};
        List<Integer> imgeList = new ArrayList<>();
        //轮播标题
        String[] mtitle = new String[]{"坚果大礼包", "彩球冰淇淋", "手撕面包", "乐事薯片系列"};
        List<String> titleList = new ArrayList<>();

        for (int i = 0; i < imageResourceID.length; i++) {
            imgeList.add(imageResourceID[i]);//把图片资源循环放入list里面
            titleList.add(mtitle[i]);//把标题循环设置进列表里面
            //设置图片加载器，通过Glide加载图片
            binding.mBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    Glide.with(SnackActivity.this).load(path).into(imageView);
                }
            });
            //设置轮播的动画效果,里面有很多种特效,可以到GitHub上查看文档。
            binding.mBanner.setBannerAnimation(Transformer.Accordion);
            binding.mBanner.setImages(imgeList);//设置图片资源
            binding.mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);//设置banner显示样式（带标题的样式）
            binding.mBanner.setBannerTitles(titleList); //设置标题集合（当banner样式有显示title时）

            //设置指示器位置（即图片下面的那个小圆点）
            binding.mBanner.setIndicatorGravity(BannerConfig.CENTER);
            binding.mBanner.setDelayTime(1000);//设置轮播时间3秒切换下一图
            binding.mBanner.setOnBannerListener(this);//设置监听
            binding.mBanner.start();//开始进行banner渲染
        }
    }

    private void postRequest(String url, Integer category) {
        new Thread(() -> {
            Map<String, String> map = new HashMap<>();
            map.put("goodsCategory", String.valueOf(category));
            String response = sendHttpRequest(url, map);
            Log.d("TAG321", "postRequest: "+response);
            goodsList = JSONObject.parseObject(response,new TypeReference<List<Goods>>(){}.getType());//将JSON字符串转换成对象
            Log.d("TAG4", "postRequest: "+ goodsList.get(1));

            runOnUiThread(() -> binding.lvList.setAdapter(getAdapter(JSONObject.parseObject(response,new TypeReference<List<Goods>>(){}.getType()))));
        }).start();
    }

    private RecyclerViewAdapter<Goods> getAdapter(List<Goods> infos){
        return new RecyclerViewAdapter<Goods>(this, R.layout.goodslist, infos) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.goodslist;

            }

            @Override
            public void convert(ViewHolder holder, Goods data, int position) {
                holder.setImage(R.id.goods_pic, data.getGoodspicture());
                holder.setText(R.id.goods_name, data.getGoodsname());

                String priceText = "￥"+data.getGoodsprice()+"/"+data.getGoodsunit();
                holder.setText(R.id.goods_price, priceText);
                holder.setOnClickListener(R.id.goods, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        Bitmap bitmap = setImage((data.getGoodsPicture()));
                            Bundle bundle = new Bundle();
                            bundle.putInt("id",data.getGoodsid());
                            Log.d("TAG5", "onClick: "+data.getGoodspicture());
                        bundle.putString("pic", data.getGoodspicture());
                            bundle.putString("name",data.getGoodsname());
                            bundle.putString("price","￥"+data.getGoodsprice()+"/"+data.getGoodsunit());
                            bundle.putString("content",data.getGoodscontent());
                            Intent intent = new Intent(SnackActivity.this,DetailsActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);

                    }
                });

            }

        };
    }

    @Override
    public void OnBannerClick(int position) {
        if(position == 0){
            Toast.makeText(this, "坚果大礼包39.9/件", Toast.LENGTH_SHORT).show();
        }
        else if(position == 1){
            Toast.makeText(this, "彩球冰淇淋9.9/盒", Toast.LENGTH_SHORT).show();
        }
        else if(position == 2){
            Toast.makeText(this, "手撕面包5.9/袋", Toast.LENGTH_SHORT).show();
        }
        else if(position == 3){
            Toast.makeText(this, "乐事薯片4.5/袋", Toast.LENGTH_SHORT).show();
        }
    }

//    private Bitmap setImage(String  imageView) {
//        return null;
//    }

}